package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.user.pojo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 授权方法，首先要根据用户名和密码跨服务访问，user-service，拿到user对象
     * 判断如果正常返回了user，则表示 用户名，密码正确，生成token
     *
     * @param username
     * @param password
     * @return
     */
    public String accredit(String username, String password) {
        try {
            User user = userClient.query(username, password);

            if (null != user) {
                //转换token
                UserInfo userInfo = new UserInfo();
                BeanUtils.copyProperties(user, userInfo);
              //根据userInfo生成token
                String token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

                return token;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
